import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

const USER_KEY="USER_KEY"
const REFRESH_TOKEN_KEY="REFRESH_TOKEN_KEY"
const ACCESS_TOKEN_KEY="ACCESS_TOKEN_KEY"

const useAuthStore = defineStore('auth', ()=>{
	const _user = ref({})
	const _refreshToken = ref('')
	const _accessToken = ref('')
	const _stsAccessKeyId = ref('')
	const _stsAccessKeySecret = ref('')
	const _stsSecurity_token = ref('')
	const _stsExpire = ref(0)


	const setUser = (user) => {
		_user.value = user
		uni.setStorageSync(USER_KEY,user)
	}

	const setRefreshToken = (token) => {
		_refreshToken.value = token
		uni.setStorageSync(REFRESH_TOKEN_KEY,token)
	}
	const setAccessToken = (access_token) => {
		_accessToken.value = access_token
		uni.setStorageSync(ACCESS_TOKEN_KEY,access_token)
	}
	const setUserToken = (user,refresh_token,access_token) => {
		setUser(user)
		setRefreshToken(refresh_token)
		setAccessToken(access_token)
	}
	const clearUserToken = () => {
		_user.value = {}
		_refreshToken.value = ''
		_accessToken.value = ''
		uni.removeStorageSync(USER_KEY)
		uni.removeStorageSync(REFRESH_TOKEN_KEY)
		uni.removeStorageSync(ACCESS_TOKEN_KEY)
	}
	const user=computed(()=>{
		if(Object.keys(_user.value).length==0){
			let user_obj=uni.getStorageSync(USER_KEY)
			if(user_obj){
				_user.value=user_obj
			}
		}
		return _user.value
	})
	const access_token=computed(()=>{
		if(!_accessToken.value){
			const token_str=uni.getStorageSync(ACCESS_TOKEN_KEY)
			if(token_str){
				_accessToken.value=token_str
			}
		}
		return _accessToken.value
	})
	const refresh_token=computed(()=>{
		if(!_refreshToken.value){
			const token_str=uni.getStorageSync(REFRESH_TOKEN_KEY)
			if(token_str){
				_refreshToken.value=token_str
			}
		}
		return _refreshToken.value
	})
	const is_logined=computed(()=>{

		if(user.value && Object.keys(user.value).length>0 && access_token.value && refresh_token.value){
			return true
		}
		return false
	})
	return {
		user,
		access_token,
		refresh_token,
		setUserToken,
		setAccessToken,
		setRefreshToken,
		clearUserToken,
		is_logined
	}
})
export default useAuthStore
